import { _decorator, Component, Node, UITransform, instantiate, Animation, EventTouch, v3 } from 'cc';
import { BaseUI } from '../../framework/base/BaseUI';
import { BaseEventName } from '../../framework/config/Appcfg';
const { ccclass, property } = _decorator;

@ccclass('UITouch')
export class UITouch extends BaseUI {
    @property(Node)
    touchNode: Node = null;
    @property({ displayName: "是否需要点击特效" })
    needEffect: boolean = true;

    private touchNodes: Node[] = []
    private isTouche: boolean = true;
    start() {
        this.addEvent(BaseEventName.blocktouch, this.onBlockTouch)
        this.node.on(Node.EventType.TOUCH_START, (event: EventTouch) => {
            if (this.needEffect) {
                let node: Node;
                if (this.touchNodes.length > 0) {
                    node = this.touchNodes.pop()
                    node.active = true;
                    node.getComponent(Animation).play();
                } else {
                    node = instantiate(this.touchNode)
                    node.active = true;
                    node.parent = this.node;
                }
                let pos = this.node.getComponent(UITransform).convertToNodeSpaceAR(v3(event.getLocation().x, event.getLocation().y))
                node.setPosition(pos)
                this.scheduleOnce(() => {
                    node.active = false;
                    this.touchNodes.push(node)
                }, 0.5)
            }
            event.preventSwallow = this.isTouche;
        })
        this.node.on(Node.EventType.TOUCH_END, (event: EventTouch) => {
            event.preventSwallow = this.isTouche;
        })
        this.node.on(Node.EventType.TOUCH_CANCEL, (event: EventTouch) => {
            event.preventSwallow = this.isTouche;
        })
        this.node.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
            event.preventSwallow = this.isTouche;
        })
        
    }

    /**是否需要阻止事件传递 */
    onBlockTouch(touched: boolean) {
        this.isTouche = touched
    }
}

